<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/25
 * Time: 14:22
 */

namespace app\service\alone\Cache;


use app\service\alone\BaseService;
use think\facade\Cache;

class ModelService extends BaseService
{
    // 缓存配置
    private $cache = [
        'config' => [],
        'model' => []
    ];

    // 是否开启缓存
    private $isCache = false;

    /**
     * 初始化配置
     */
    protected function init()
    {
        // 是否有缓存配置
        if($this -> cache = config('databaseCache')) {
            $this -> isCache = true;

            // 是否启用缓存配置
            if(!$this -> cache['config']['cache']) $this -> isCache = false;
        }
    }

    /**
     * 缓存配置
     *
     * @param string $className
     * @return array
     */
    public function boot(string $className):array{
        // 是否启用缓存
        if(!$this -> isCache) return [];

        // 匹配当前模型名称，是否需要开启缓存
        if(!isset($this -> cache['model'][$className]) || !$config = $this -> cache['model'][$className]) return [];

        // 当前模型下是否需要开启缓存
        if(isset($config['cache'])) if(!$config['cache']) return [];

        // 替换缓存的缓存时间
        $config['cache_time'] = $config['cache_time'] ?? $this -> cache['config']['cache_time'];

        return $config;
    }

    /**
     * 设置缓存
     *
     * @param array $config 缓存配置
     * @param object $query
     * @param string $mark  缓存标识
     * @return object
     */
    public function setCache(array $config, object $query, string $mark):object {
        $query -> cache($mark, $config['cache_time'], $config['cache_tag']);

        return $query;
    }

    /**
     * 清除当前模型所有缓存
     *
     * @param array $config
     */
    public function clearCache(array $config){
        Cache::tag($config['cache_tag']) -> clear();
    }
}
